<template>
  <div class="myDialog">
    <!-- 弹窗组件 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="title"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      width="40%"
    >
      <el-form
        ref="ruleForm"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="$t('projectCode')" prop="code">
          <el-input
            v-model.trim="form.code"
            :disabled="form.id?true:false"
            onkeyup="this.value = this.value.replace(/[\u4e00-\u9fa5]/ig,'')"
            style="width: 100%" />
        </el-form-item>
        <el-form-item :label="$t('projectName')" prop="name">
          <el-input v-model.trim="form.name" style="width: 100%" />
        </el-form-item>
        <el-form-item :label="$t('adminAccount')" prop="admin">
          <el-input v-model.trim="form.admin" :disabled="form.id?true:false" style="width: 100%"/>
        </el-form-item>
        <el-form-item :label="$t('manager')" prop="manager">
          <el-input v-model.trim="form.manager" style="width: 100%" />
        </el-form-item>
        <el-form-item label="Logo">
          <el-upload
            :action="updateAvatarApi"
            :show-file-list="false"
            :on-success="handleChangeImg"
            :headers="headers"
            :file-list="fileList"
            accept=".PNG, .JPG, .GIF"
          >
            <img v-if="form.logo||imageUrl" :src="imgUrlFormatter(form.logo)||imageUrl">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="mini logo">
          <el-upload
            :action="updateAvatarApi"
            :show-file-list="false"
            :on-success="handleChangeMiniLogo"
            :headers="headers"
            :file-list="fileList"
            accept=".PNG, .JPG, .GIF"
          >
            <img v-if="form.minilogo||miniLogoUrl" :src="imgUrlFormatter(form.minilogo)||miniLogoUrl">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="选择产品" prop="modules">
          <el-select v-model.trim="form.modules" multiple style="width: 100%" >
            <el-option
              v-for="item in modulesList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="License" prop="license">
          <el-input
            v-model.trim="form.license"
            style="width: 100%"
            rows="4"
            type="textarea"
          />
        </el-form-item>
        <el-form-item :label="$t('description')" prop="description">
          <el-input
            v-model.trim="form.description"
            style="width: 100%"
            rows="4"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button icon="el-icon-circle-close" @click="closeDialog">{{
          $t("cancel")
        }}</el-button>
        <el-button
          v-btnThrottle="doSave"
          type="primary"
          icon="el-icon-receiving"
        >{{ $t('save') }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import projectApi from '@/api/system/project'
import mySetting from '@/mixins/mySetting'
import networkTips from '@/mixins/networkTips'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
export default {
  name: 'MyDialog',
  mixins: [mySetting, networkTips],
  data() {
    return {
      headers: {
        Token: getToken()
      },
      title: '',
      form: {},
      modulesList: [],
      dialogFormVisible: false,
      imageUrl: '',
      miniLogoUrl: '',
      fileList: [], // 上传图片列表
      rules: {
        code: [
          { required: true, message: this.$t('projectCodeRequired'), trigger: 'blur' },
          { min: 4, max: 8, message: this.$t('fourLength'), trigger: 'blur' }
        ],
        name: [{ required: true, message: this.$t('projectNameRequired'), trigger: 'blur' }],
        admin: [
          { required: true, message: this.$t('adminAccountRequired'), trigger: 'blur' }
        ],
        license: [
          { required: true, message: '请输入license', trigger: 'blur' }
        ]
      } // 表单校验规则
    }
  },
  computed: {
    ...mapGetters(['updateAvatarApi', 'baseApi'])
  },
  methods: {
    // 新增数据
    doSave() {
      this.$refs['ruleForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if (this.form.id) {
          // 存在id则是更新
          projectApi.edit({ id: this.form.id, ...this.form }).then((res) => {
            this.netTips(res, this.closeDialog, this.handleUpdate)
          })
        } else {
          // 不存在id则是新增
          projectApi.add(this.$clearNull(this.form)).then((res) => {
            this.netTips(res, this.closeDialog, this.handleUpdate)
          })
        }
      })
    },
    // 打开弹窗
    openDialog(row) {
      if (row && row.id) {
        // 这get接口名字起太糟糕了
        projectApi.get({ id: row.id }).then(res => {
          this.form = res.data
          this.title = this.$t('modifyProject')
        })
      } else {
        this.title = this.$t('addProject')
      }
      this.dialogFormVisible = true
      this.getEnEnumList()
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate()
      })
    },
    // 关闭弹窗
    closeDialog() {
      Object.assign(this.$data, this.$options.data.call(this))
    },
    // 触发父组件更新
    handleUpdate() {
      this.$emit('initList')
    },
    // 上传图片成功
    handleChangeImg(response) {
      this.imageUrl = `${this.baseApi}/${response.data}`
      this.form.logo = response.data
    },
    handleChangeMiniLogo(response) {
      this.miniLogoUrl = `${this.baseApi}/${response.data}`
      this.form.minilogo = response.data
    },
    imgUrlFormatter(url) {
      if (url === '' || url == null || url === undefined) return
      // 当图片路径相同时,即使源图片更改了,img内显示的也不会去刷新,需要在后面加radom或者当前时间去解决
      return this.baseApi + '/' + url + '?t=' + new Date()
    },
    async getEnEnumList() {
      const res = await projectApi.getEnEnumList({ enumName: 'ProductModule' })
      this.modulesList = res.data
    }
  }
}
</script>
<style lang="scss" scoped>
.el-image {
  width: 150px;
  height: 150px;
}
.el-upload{
  img{
    width: 100px;
    height: 100px;
  }
}
</style>
